import { Button, Form, Input, Modal } from 'tea-component';
import { Controller, useForm } from 'react-hook-form';
import { getStatus } from '../../utils/form-utils';
import React, { useEffect } from 'react';
import { useFetchJoinChain } from '../../common/apis/chains/hooks';

interface IGenerateJoinChainModalParam {
  visible: boolean;
  close: () => void;
  successCallback?: () => void;
}

interface IInitialData {
  ChainCode: string;
}

export function GenerageJoinChainModal({ visible, close, successCallback }: IGenerateJoinChainModalParam) {
  const {
    control,
    handleSubmit,
    reset,
    formState: { errors, isValidating, isSubmitted, isValid },
  } = useForm({
    mode: 'onBlur',
    defaultValues: {} as any,
  });

  const { fetch } = useFetchJoinChain();

  const submit = async (values: IInitialData) => {
    await fetch({
      ChainCode: values.ChainCode,
    });
    successCallback?.();
  };

  useEffect(() => {
    if (visible) {
      reset();
    }
  }, [visible]);

  return (
    <Modal caption="加入区块链" visible={visible} onClose={close}>
      <Modal.Body>
        <Form>
          <Controller
            name="ChainCode"
            control={control}
            defaultValue={''}
            render={({ field, fieldState }) => (
              <Form.Item
                label="区块链分享码"
                required
                status={isValidating ? 'validating' : getStatus({ fieldState, isSubmitted, isValidating })}
                message={errors.ChainCode?.message}
              >
                <Input placeholder="请输入区块链分享码" size="full" {...field} />
              </Form.Item>
            )}
          />
        </Form>
      </Modal.Body>
      <Modal.Footer>
        <Button type="primary" disabled={!isValid} onClick={handleSubmit(submit)}>
          确定
        </Button>
        <Button onClick={close}>取消</Button>
      </Modal.Footer>
    </Modal>
  );
}
